/*
 * @Author: your name
 * @Date: 2021-04-26 18:05:17
 * @LastEditTime: 2021-05-12 11:41:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /emotech-wxapp/src/utils/request.js
 */
import Taro from '@tarojs/taro'
import { baseUrl, defaultEmToken } from './config'

const request = (options) => {
  return new Promise((resolve, reject) => {
    const userInfo = Taro.getStorageSync('userInfo') || {}
    Taro.request({
      url: baseUrl + options.url,
      method: options.method || 'GET',
      data: options.data,
      header: {
        token: userInfo.token ? userInfo.token : defaultEmToken,
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          if (res.data && res.data.success) {
            resolve(res.data.data)
          } else {
            Taro.showToast({
              title: '网络不好,请重试',
              icon: 'error',
              duration: 2000
            })
            console.log('接口错误, url', options.url, res)
            reject(res)
          }
        } else {
          Taro.showToast({
            title: '网络不好,请重试',
            icon: 'error',
            duration: 2000
          })
          reject(res)
        }
      },
      fail: (err) => {
        console.log('接口错误, url', options.url, err)
        reject(err)
      }
    })
  })
}

export default request
